﻿using Newtonsoft.Json;
using Sunny.UI.Win32;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.Model;
using WinApp.Model.AjaxResult;
using WinApp.Until;
using WinApp.ViewModel;
using WinApp.i18n;

namespace WinApp
{
    public partial class LoginIndex : Form
    {
        private const string PasswordFileName = "password.txt";
        public LoginIndex()
        {
            InitializeComponent();
            linkLabel1.AutoSize = true;
            pictureBox1.Image = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/plane.png");
        }

        private void LoginIndex_Load(object sender, EventArgs e)
        {
            //SetFormRoundRectRgn(this,20);    //设置圆角
            //this.BackColor = Color.Gray;
            button1.FlatStyle = FlatStyle.Flat;
            button1.FlatAppearance.BorderSize = 0; // 设置边框宽度为 0
            RoundHelper.SetButtonRoundRectRgn(button1, 15);    //设置圆角            


            // 从文件中读取保存的密码
            string savedPassword = ReadPasswordFromFile();
            if (!string.IsNullOrEmpty(savedPassword))
            {
                // 将 JSON 字符串反序列化为 Person 对象
                LoginInputDto RememberInfo = JsonConvert.DeserializeObject<LoginInputDto>(savedPassword);

                // 解密密码
                string decryptedPassword = Decrypt(RememberInfo.Password);
                // 填充密码框
                txtPwd.Text = decryptedPassword;
                txtCode.Text = RememberInfo.UserName;

                // 设置记住密码复选框为选中状态
                cbRemember.Checked = true;
            }

            uiSwitch1.Active = false;
            uiSwitch1.ActiveText = Language.GetLang("onLine");
            uiSwitch1.InActiveText = Language.GetLang("offLine");
            string strSwichModel = UtilHelper.ReadSwitchMode();
            if (!string.IsNullOrEmpty(strSwichModel))
            {
                if (strSwichModel == SwitchMode.OnLine)
                {
                    uiSwitch1.Active = true;
                }
            }


        }
        //private void Form1_Load(object sender, EventArgs e)
        private void button1_ClickAsync(object sender, EventArgs e)
        {
            var _code = txtCode.Text.Trim();
            var _pwd = txtPwd.Text.Trim();

            //验证输入合法性....
            if (string.IsNullOrEmpty(_code))
            {
                MessageBox.Show("Code is null");
                return;
            }
            if (string.IsNullOrEmpty(_pwd))
            {
                MessageBox.Show("Password is null");
                return;
            }

            //验证用户信息....

            string username = txtCode.Text.Trim();
            string password = txtPwd.Text.Trim();

            // 验证用户名和密码
            if (cbRemember.Checked)
            {
                var loginData = new LoginInputDto
                {
                    UserName = username,
                    Password = password,
                };
                // 加密密码
                loginData.Password = Encrypt(password);

                // 保存加密后的密码到文件
                SavePasswordToFile(loginData);
            }
            else
            {
                // 删除保存的密码文件
                DeletePasswordFile();
            }

            var result = LoginIndexModel.token(new LoginInfoInputDto
            {
                account = _code,
                password = _pwd,
                grantType = "password",
                IsForceLogin = true,
                tenantId = -1
            });
            if (result == null)
                return;
            if (result.Type == AjaxResultType.Success)
            {
                // 进行登录操作
                this.DialogResult = DialogResult.OK;

            }
            else
            {
                UIMessageDialog.ShowMessageDialog(result.Content, UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
            }
        }

        private void SavePasswordToFile(LoginInputDto dto)
        {
            // 将 Person 对象序列化为 JSON 字符串
            string strLoginDto = JsonConvert.SerializeObject(dto);
            System.IO.File.WriteAllText(PasswordFileName, strLoginDto);
        }

        private string Encrypt(string password)
        {
            // 使用加密算法加密密码
            // TODO: 实现加密算法
            return password;
        }

        private string Decrypt(string encryptedPassword)
        {
            // 使用解密算法解密密码
            // TODO: 实现解密算法
            return encryptedPassword;
        }
        private string ReadPasswordFromFile()
        {
            if (System.IO.File.Exists(PasswordFileName))
            {
                return System.IO.File.ReadAllText(PasswordFileName);
            }
            return "";
        }

        private void DeletePasswordFile()
        {
            if (System.IO.File.Exists(PasswordFileName))
            {
                System.IO.File.Delete(PasswordFileName);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string websiteUrl = @"https://test.astrom.cn/#/passport/forgot-password";
            OpenWebPage(websiteUrl);
        }

        public static void OpenWebPage(string url)
        {
            try
            {
                Process.Start(new ProcessStartInfo(url));
            }
            catch (Exception)
            {
                // 如果直接用URL启动失败（例如在某些旧版Windows上），可以尝试显式调用浏览器程序
                string browserPath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"; // 以谷歌浏览器为例
                if (File.Exists(browserPath))
                {
                    Process.Start(new ProcessStartInfo(browserPath, url));
                }
                else
                {
                    // 或者尝试启动IE浏览器
                    Process.Start("iexplore.exe", url);
                }
            }
        }

        private void uiSwitch1_ValueChanged(object sender, bool value)
        {
            if (value)
            {//在线
                UtilHelper.SetSwitchMode(SwitchMode.OnLine);
            }
            else
            {//离线
                UtilHelper.SetSwitchMode(SwitchMode.OffLine);
            }
        }
    }


}
